package com.leet.code.lcof;

import com.algorithm.model.ListNode;

public class Code22 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        head.next = head2;
        head2.next = head3;

        ListNode listNode = new Code22().getKthFromEnd(head, 3);

        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public ListNode getKthFromEnd1(ListNode head, int k) {
        ListNode[] listNodes = new ListNode[k];
        int i = 0;
        while (head != null) {
            listNodes[i] = head;
            i++;
            if (i == k) {
                i = 0;
            }
            head = head.next;
        }
        return listNodes[i];
    }

    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode start = head, end = head;
        for (; k > 0; k--) {
            end = end.next;
        }
        while (end != null) {
            end = end.next;
            start = start.next;
        }
        return start;
    }


}
